<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
<script>
    let a = 1
    let b = 2
    b = 3
    console.log('浅拷贝:', a, b)

    let arr = [1, 2, 3]
    let arr2 = arr // 浅
    arr.push(4)
    console.log('深拷贝:', arr, arr2)

    let obj = {
        name: 'jack',
        age: 22,
        friends: {
            name: 'marry',
            age: 21
        }
    }

    // 浅拷贝 把所有属性的值（不是引用！！）复制过来，但只能一层，不能递归到里面的
    function copy(to, from) {
        for (var key in from) {
            to[key] = from[key]
        }
        return to
    }

    // 深拷贝：修改一个不会影响另一个，拷贝了引用上的值，独立开了
    let myObj = copy({}, obj)
    myObj.name = 18
    console.log(myObj)

    // 浅拷贝（拷贝的是引用地址）： 修改之后会影响的，修改了引用的那个地址上的值
    let obj2 = obj
    obj2.name = 'kkk'
    console.log(obj2)
    console.log(obj)
    let cook = {
        name: 'jack',
        count: 1,
        world: {
            name: '佐料',
            count: 5,
            world: {
                name: '食盐',
                count: 10,
                world: {
                    name: '筷子',
                    count: 15
                }
            }
        }
    }

    // 深拷贝   遍历 对象的所有属性
    function deepCopy(to, from) {
        for (let key in from) {
            // 内层对象
            console.log(from.hasOwnProperty(key))
            // 不遍历原型链上的值
            if (from.hasOwnProperty(key)) {
                // 值是对象并且有值
                if (from[key] && typeof from[key] === 'object') {
                    to[key] = from[key].constructor === Array ? [] : {}
                    console.log(to[key])
                    to[key] = deepCopy(to[key], from[key])
                } else {
                    to[key] = from[key]
                }
            }
        }
        return to
    }

    console.log(deepCopy({}, cook))
</script>
</body>

</html>
